import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.less']
})
export class SigninComponent implements OnInit {


  public signForm:{
    email:string,
    password:string
  } = {
    email:'',
    password:''
  }

  public error_message:string;

  constructor(private http:HttpClient,private router:Router) { }

  ngOnInit() {
  }

  signInHandler(){
    this.http.post('http://localhost:3000/session',this.signForm)
      .toPromise()
      .then((res:any)=>{
        this.error_message = '';
        window.localStorage.setItem('auth_token',res.token);
        window.localStorage.setItem('userInfo',JSON.stringify(res.user));
        this.router.navigate(['/contacts'])
      }).catch(err=>{
        if(err.status==401){
           this.error_message = '用户名或者密码不对';
        }
      })
  }

}
